package com.hkts.naturalgas.performance.service.serviceimpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.hkts.naturalgas.constant.PerformanceConstant;
import com.hkts.naturalgas.feign.FeignFlow;
import com.hkts.naturalgas.feign.FeignInterface;
import com.hkts.naturalgas.flow.entity.FlowInstanceinfo;
import com.hkts.naturalgas.flow.mapper.FlowInstanceinfoMapper;
import com.hkts.naturalgas.flow.service.IFlowInstanceinfoService;
import com.hkts.naturalgas.flow.service.IFlowTaskInstanceService;
import com.hkts.naturalgas.index.entity.ParamVo;
import com.hkts.naturalgas.index.service.serviceimpl.IndexServiceImpl;
import com.hkts.naturalgas.organizational.entity.*;
import com.hkts.naturalgas.organizational.mapper.*;
import com.hkts.naturalgas.performance.entity.*;
import com.hkts.naturalgas.performance.mapper.*;
import com.hkts.naturalgas.performance.performanceTo.HontUserTo;
import com.hkts.naturalgas.performance.performanceTo.PerformanceTo;
import com.hkts.naturalgas.performance.performanceTo.SubmitPerformanceDTo;
import com.hkts.naturalgas.performance.performanceVo.*;
import com.hkts.naturalgas.performance.service.IHkAssessmentInfoService;
import com.hkts.naturalgas.performance.service.IHkAssessmentPictureService;
import com.hkts.naturalgas.performance.service.IHkAssessmentScoreService;
import com.hkts.naturalgas.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author yck
 * @since 2020-12-16
 */
@Service
@Transactional
@Slf4j
public class HkAssessmentScoreServiceImpl extends ServiceImpl<HkAssessmentScoreMapper, HkAssessmentScore> implements IHkAssessmentScoreService {

    @Autowired
    public IHkAssessmentPictureService iHkAssessmentPictureService;
    @Autowired
    private HkAssessmentScoreMapper hkAssessmentScoreMapper;
    @Autowired
    private HkAssessmentInfoMapper hkAssessmentInfoMapper;
    @Autowired
    private HontUserRoleMapper hontUserRoleMapper;
    @Autowired
    private HontRoleMapper hontRoleMapper;
    @Autowired
    private HontUserMapper hontUserMapper;
    @Autowired
    private HontDepartmentMapper hontDepartmentMapper;
    @Autowired
    private FeignInterface feignInterface;
    @Autowired
    private HkAssessmentPictureMapper hkAssessmentPictureMapper;
    @Autowired
    private HkAssessmentIndexMapper hkAssessmentIndexMapper;
    @Autowired
    public IHkAssessmentInfoService iHkAssessmentInfoService;
    @Autowired
    private HkFormEntityMapper hkFormEntityMapper;

    @Autowired
    public IFlowInstanceinfoService flowInstanceinfoService;
    @Autowired
    public IFlowTaskInstanceService iFlowTaskInstanceService;
    @Autowired
    private FlowInstanceinfoMapper flowInstanceinfoMapper;
    @Autowired
    private HontPostMapper hontPostMapper;
    @Autowired
    private IndexServiceImpl indexService;

    @Autowired
    private FeignFlow feignFlow;

    @Autowired
    public RedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public IPage<HkAssessmentScore> selectPage(Page<HkAssessmentScore> page, HkAssessmentScore hkAssessmentScore) {
        QueryWrapper<HkAssessmentScore> query = Wrappers.query();
        QueryWrapper<HkAssessmentScore> entityWrapper = getEntityWrapper(query, hkAssessmentScore);
        return hkAssessmentScoreMapper.selectPage(page, entityWrapper);
    }


    @Override
    public List<HkAssessmentScore> selectList(HkAssessmentScore hkAssessmentScore) {
        QueryWrapper<HkAssessmentScore> query = Wrappers.query();
        QueryWrapper<HkAssessmentScore> entityWrapper = getEntityWrapper(query, hkAssessmentScore);
        return hkAssessmentScoreMapper.selectList(entityWrapper);
    }

    /**
     * 处理绩效提交的业务逻辑
     *
     * @param performanceTo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveScoreAndForm(PerformanceTo performanceTo) throws Exception {
        HontUserTo hontUserTo = feignInterface.remoteUserInfo();
        /*
         * 分部式锁
         * */
        RLock lock = redissonClient.getLock(performanceTo.getSubmissionKey());
        lock.lock();
        try {

            Object o = redisTemplate.opsForValue().get(PerformanceConstant.SUBMISSION_KEY + performanceTo.getSubmissionKey());
            if (o == null) {
                throw new Exception("请勿重复提交！");
            }
        /*    else {
                redisTemplate.delete(PerformanceConstant.SUBMISSION_KEY + performanceTo.getSubmissionKey());
            }*/
            Gson gson = new Gson();
            List<Map<String, Object>> listVo = new ArrayList<Map<String, Object>>();
            Result<Map<String, Object>> result = feignInterface.performanceUserInfo();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日");
            SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
            Date parse = dateFormat.parse(performanceTo.getCreateTime());
            String format = dateFormat1.format(parse);
            Map<String, Object> result1 = result.getResult();
            String identity = result1.get("identity").toString();
            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDateTime ldt = LocalDate.parse(format, DateTimeFormatter.ISO_DATE).atStartOfDay();
            LocalDateTime now = LocalDateTime.now();
            // Result add = feignFlow.add(performanceTo.getHountUserId());
            //流程实例id
            String add = feignFlow.add(performanceTo.getHountUserId());
            System.out.println("流程创建成功！！！！！！！！");//3b7877eb646411ebae764244a072280e
            if (add.length() < 30 || add.length() > 40) {
                throw new Exception("网络异常请联系管理员处理");
            }
            performanceTo.setProcessInstanceId(add);
            HontUser hontUser = hontUserMapper.selectById(performanceTo.getHountUserId());
            /*
             * 提交信息
             * */
            String assessmentInfoName = hontUserTo.getNickName() + "提交了" + hontUser.getNickName() + performanceTo.getCreateTime() + "的考核";
            HkAssessmentInfo info = new HkAssessmentInfo();
            if (!identity.equals("5")) {
                info.setAssessmentStatus("1");
            } else {
                info.setAssessmentStatus("2");
            }
            info.setId(IDUtils.genImageName());
            info.setCreateBy(hontUserTo.getId());
            info.setCreateTime(ldt);
            info.setProcessInstanceId(performanceTo.getProcessInstanceId());
            info.setAssessmentName(assessmentInfoName);
            hkAssessmentInfoMapper.insert(info);
            /*yck
             * 操作score表数据
             * 角色级别还没有设置
             * */
            List<Map<String, Object>> list = gson.fromJson(performanceTo.getList(), listVo.getClass());

            for (int i = 0; i < list.size(); i++) {
                HkAssessmentScore score = new HkAssessmentScore();
                if (list.get(i).get("indexFrequency") == null || list.get(i).get("indexFrequency").toString().equals("") || Float.parseFloat(list.get(i).get("indexFrequency").toString()) == 0) {
                    continue;
                }
                if (list.get(i).get("indexId").toString().equals(PerformanceConstant.IS_CUSTOM_DELETE)) {
                    score.setScore(-Float.parseFloat(list.get(i).get("indexFrequency").toString()));
                    score.setIndexFrequency((int) Float.parseFloat(list.get(i).get("indexFrequency").toString()));
                    if (list.get(i).get("indexComment") != null) {
                        score.setIndexDescribe(list.get(i).get("indexComment").toString());
                    }
                    score.setIndexName("自定义减分项");

                } else if (list.get(i).get("indexId").toString().equals(PerformanceConstant.IS_CUSTOM_ADD)) {
                    score.setScore(Float.parseFloat(list.get(i).get("indexFrequency").toString()));
                    score.setIndexFrequency((int) Float.parseFloat(list.get(i).get("indexFrequency").toString()));
                    if (list.get(i).get("indexComment") != null) {
                        score.setIndexDescribe(list.get(i).get("indexComment").toString());
                    }
                    score.setIndexName("自定义加分项");
                } else {
                    score.setScore(Float.parseFloat(list.get(i).get("indexFrequency").toString()) * Float.parseFloat(list.get(i).get("indexScore").toString()));
                    score.setIndexDescribe(list.get(i).get("indexDescribe").toString());
                    score.setIndexFrequency((int) Float.parseFloat(list.get(i).get("indexFrequency").toString()));
                    score.setIndexName(list.get(i).get("indexName").toString());
                }
                score.setApprovalUserId(hontUserTo.getId());
                score.setHontUserId(performanceTo.getHountUserId());
                score.setId(IDUtils.genImageName());
                score.setIndexId(list.get(i).get("indexId").toString());
                if (!identity.equals("5")) {
                    score.setScoreState("1");
                } else {
                    score.setScoreState("2");
                }
                score.setIndexComment(list.get(i).get("indexComment").toString());
                score.setCreateTime(now);
                score.setIsCurrentAssessment("1");
                score.setRoleLevel(identity);
                score.setNumId(list.get(i).get("numId").toString());
                score.setTxtId(list.get(i).get("txtId").toString());

                /*
                 *处理图片数据
                 * */
                if (list.get(i).get("imgList") != null) {
                    List imgList = (List) list.get(i).get("imgList");
                    iHkAssessmentPictureService.saveImageByProcessAndItem(performanceTo.getProcessInstanceId(), score.getIndexId(), imgList);
                }
                score.setProcessInstanceId(performanceTo.getProcessInstanceId());
                hkAssessmentScoreMapper.insert(score);
            }
            /*
             * 业务执行成功后用来判断是否需要发送消息
             * */
            if (identity.equals("5")) {
                sendMessage(hontUser.getId());
            }
            //删除key 防止用户重复提交
            redisTemplate.delete(PerformanceConstant.SUBMISSION_KEY + performanceTo.getSubmissionKey());

        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception(e.getMessage());
        } finally {
            lock.unlock();
        }
    }

    /**首次提交考核
     * 处理绩效提交的业务逻辑（v1.5）
     *
     * @param submitPerformanceDTo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveScoreAndFormTo(SubmitPerformanceDTo submitPerformanceDTo) throws Exception {
        HontUserTo hontUserTo = feignInterface.remoteUserInfo();
        HontUser hontUser = hontUserMapper.selectById(submitPerformanceDTo.getHontUserId());
        String createTime = URLDecoder.decode(submitPerformanceDTo.getCreateTime(), "UTF-8");
        FlowInstanceinfo flowInstanceinfo = new FlowInstanceinfo();
        flowInstanceinfo.setTemplateId(submitPerformanceDTo.getFlowId());
        flowInstanceinfo.setHontUserId(submitPerformanceDTo.getHontUserId());
        flowInstanceinfo.setHontUserName(hontUser.getNickName());
        flowInstanceinfo.setHontDepartmentId(hontUser.getDepartmentId());
        flowInstanceinfo.setTemplateVersion(submitPerformanceDTo.getTemplateVersion());
        Result<Object> objectResult = flowInstanceinfoService.initiateProcess(flowInstanceinfo);
        log.info("获取流程数据：{}", objectResult);
        String instanceinfo = "";
        Map data = new HashMap();
        if (objectResult.getCode() == 500) {
            throw new Exception(objectResult.getMessage());
        }
        data = BeanConvertUtils.objectToMap(objectResult.getResult());
        if (data.get("instanceinfo") != null) {
            instanceinfo = data.get("instanceinfo").toString();
            submitPerformanceDTo.setProcessInstanceId(instanceinfo);
        } else {
            throw new Exception("暂无流程节点信息");
        }


        ;
        /*
         * 分部式锁
         * */
        RLock lock = redissonClient.getLock(submitPerformanceDTo.getSubmissionKey());
        lock.lock();

        try {
            Object o = redisTemplate.opsForValue().get(PerformanceConstant.SUBMISSION_KEY + submitPerformanceDTo.getSubmissionKey());
            if (o == null) {
                throw new Exception("请勿重复提交！");
            }
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日");
            SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
            Date parse = dateFormat.parse(createTime);
            String format = dateFormat1.format(parse);
            LocalDateTime ldt = LocalDate.parse(format, DateTimeFormatter.ISO_DATE).atStartOfDay();
            LocalDateTime now = LocalDateTime.now();
            HontPost hontPost = hontPostMapper.selectById(submitPerformanceDTo.getHontPostId());
            /*
             * 提交信息
             * */
            String assessmentInfoName = hontUserTo.getNickName() + "提交了" + hontUser.getNickName() + createTime + "的考核";
            HkAssessmentInfo info = new HkAssessmentInfo();
            boolean finish = false;
            //当前登录人等级
            if (data.get("finish") != null) {
                finish = Boolean.parseBoolean(data.get("finish").toString());
                if (finish) {
                    info.setAssessmentStatus("2");
                    info.setEndTime(LocalDateTime.now());
                } else {
                    info.setAssessmentStatus("1");
                }
            } else {
                throw new Exception("未查询到该节点人员信息！");
            }
            info.setHontPostId(hontPost.getId());
            info.setHontPostTitle(hontPost.getTitle());
            info.setId(IDUtils.genImageName());
            info.setCreateBy(hontUserTo.getId());
            info.setCreateTime(ldt);
            info.setProcessInstanceId(submitPerformanceDTo.getProcessInstanceId());
            info.setAssessmentName(assessmentInfoName);
            info.setHontUserId(hontUser.getId());
            info.setNickName(hontUser.getNickName());
            info.setFormKey(submitPerformanceDTo.getFormId());
            if (StringUtils.isNotBlank(hontUser.getDepartmentId())) {
                info.setDepartmentId(hontUser.getDepartmentId());
                HontDepartment hontDepartment = hontDepartmentMapper.selectById(hontUser.getDepartmentId());
                info.setDepartmentTitle(hontDepartment.getTitle());
            }
            HkFormEntity hkFormEntity = hkFormEntityMapper.selectById(submitPerformanceDTo.getFormId());
            info.setBusinessType(hkFormEntity.getActTypeId());
            info.setFlowTemplateId(submitPerformanceDTo.getFlowId());
            /*yck
             * 操作score表数据
             * 角色级别还没有设置
             * */
            List<IndexAndFormIdVo> list = submitPerformanceDTo.getList();
            Float score1 = (float) 0;
            for (int i = 0; i < list.size(); i++) {
                HkAssessmentScore score = new HkAssessmentScore();
                if (list.get(i).getIndexFrequency() == null || list.get(i).getIndexFrequency().toString().equals("") || Float.parseFloat(list.get(i).getIndexFrequency().toString()) == 0) {
                    continue;
                }
                if (list.get(i).getIndexType() == 2) {
                    score.setIndexFrequency((int) Float.parseFloat(list.get(i).getIndexFrequency().toString()));
                    if (StringUtils.isNotBlank(list.get(i).getScoreType()) && list.get(i).getScoreType().equals(HkAssessmentIndex.SCORE_TYPE_DELETE)) {
                        score.setScore(Float.parseFloat(list.get(i).getIndexFrequency().toString()));
                    } else if (StringUtils.isNotBlank(list.get(i).getScoreType()) && list.get(i).getScoreType().equals(HkAssessmentIndex.SCORE_TYPE_ADD)) {
                        score.setScore(Float.parseFloat(list.get(i).getIndexFrequency().toString()));
                    }
                } else if (list.get(i).getIndexType() == 3) {
                    score.setScore(Float.parseFloat(list.get(i).getIndexFrequency().toString()));
                    score.setIndexFrequency((int) Float.parseFloat(list.get(i).getIndexFrequency().toString()));
                } else if (list.get(i).getIndexType() == 4) {
                    score.setScore(-Float.parseFloat(list.get(i).getIndexFrequency().toString()));
                    score.setIndexFrequency((int) Float.parseFloat(list.get(i).getIndexFrequency().toString()));
                } else {
                    score.setScore(Float.parseFloat(list.get(i).getIndexFrequency().toString()) * Float.parseFloat(list.get(i).getIndexScore()));
                    score.setIndexFrequency((int) Float.parseFloat(list.get(i).getIndexFrequency().toString()));
                }
                score.setIndexDescribe(list.get(i).getIndexDescribe());
                score.setIndexName(list.get(i).getIndexName());
                score.setScoreType(list.get(i).getScoreType());
                score.setApprovalUserId(hontUserTo.getId());
                score.setHontUserId(submitPerformanceDTo.getHontUserId());
                score.setId(IDUtils.genImageName());
                score.setIndexId(list.get(i).getIndexId());
                if (finish) {
                    score.setScoreState("2");
                } else {
                    score.setScoreState("1");
                }
                score.setIndexComment(list.get(i).getIndexComment());
                score.setCreateTime(now);
                score.setIsCurrentAssessment("1");

                /*
                 *处理图片数据
                 * */
                if (list.get(i).getImglist().size() > 0) {
                    List imgList = list.get(i).getImglist();
                    iHkAssessmentPictureService.saveImageByProcessAndItem(submitPerformanceDTo.getProcessInstanceId(), score.getIndexId(), imgList);
                }
                score.setProcessInstanceId(submitPerformanceDTo.getProcessInstanceId());
                hkAssessmentScoreMapper.insert(score);
                score1 += score.getScore();
            }
            if (score1 == 0 || score1 == null){
                throw new Exception("请勿提交分数为0的考核！");
            }
            info.setAssessmentScore(score1);
            hkAssessmentInfoMapper.insert(info);
            /*
             * 业务执行成功后用来判断是否需要发送消息
             * */
            if (finish) {
                sendMessage(hontUser.getId());
            }
            redisTemplate.delete(PerformanceConstant.SUBMISSION_KEY + submitPerformanceDTo.getSubmissionKey());
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        } finally {
            lock.unlock();
        }

    }

    /**
     * 公共查询条件
     *
     * @param entityWrapper
     * @return
     */
    public QueryWrapper<HkAssessmentScore> getEntityWrapper(QueryWrapper<HkAssessmentScore> entityWrapper, HkAssessmentScore hkAssessmentScore) {
        //条件拼接
        if (StringUtils.isNotBlank(hkAssessmentScore.getApprovalUserId())) {
            entityWrapper.like(HkAssessmentScore.APPROVAL_USER_ID, hkAssessmentScore.getApprovalUserId());
        }
        if (StringUtils.isNotBlank(hkAssessmentScore.getHontUserId())) {
            entityWrapper.like(HkAssessmentScore.HONT_USER_ID, hkAssessmentScore.getHontUserId());
        }
        if (StringUtils.isNotBlank(hkAssessmentScore.getIndexDescribe())) {
            entityWrapper.like(HkAssessmentScore.INDEX_DESCRIBE, hkAssessmentScore.getIndexDescribe());
        }
        if (StringUtils.isNotBlank(hkAssessmentScore.getIndexId())) {
            entityWrapper.like(HkAssessmentScore.INDEX_ID, hkAssessmentScore.getIndexId());
        }
        if (StringUtils.isNotBlank(hkAssessmentScore.getIndexName())) {
            entityWrapper.like(HkAssessmentScore.INDEX_NAME, hkAssessmentScore.getIndexName());
        }
        if (StringUtils.isNotBlank(hkAssessmentScore.getProcessInstanceId())) {
            entityWrapper.like(HkAssessmentScore.PROCESS_INSTANCE_ID, hkAssessmentScore.getProcessInstanceId());
        }
        if (StringUtils.isNotBlank(hkAssessmentScore.getRoleLevel())) {
            entityWrapper.like(HkAssessmentScore.ROLE_LEVEL, hkAssessmentScore.getRoleLevel());
        }

        if (StringUtils.isNotBlank(hkAssessmentScore.getScoreState())) {
            entityWrapper.like(HkAssessmentScore.SCORE_STATE, hkAssessmentScore.getScoreState());
        }
        if (StringUtils.isNotBlank(hkAssessmentScore.getIsCurrentAssessment())) {
            entityWrapper.eq(HkAssessmentScore.IS_CURRENT_ASSESSMENT, hkAssessmentScore.getIsCurrentAssessment());
        }
        return entityWrapper;
    }
    /*
     * 流程实例完成之后将数据修改为审核完成
     * */

    @Override
    @Transactional
    public void updateStateByProcessInstanceId(HkAssessmentScore score) {
        hkAssessmentScoreMapper.updateStateByProcessInstanceId(score);
        HkAssessmentInfo info = new HkAssessmentInfo();
        info.setProcessInstanceId(score.getProcessInstanceId());
        QueryWrapper<HkAssessmentInfo> query = Wrappers.query();
        query.eq("process_instance_id", score.getProcessInstanceId());
        hkAssessmentInfoMapper.updateStatusByProcessInstanceId(score.getProcessInstanceId());
        /*
         * 远程调用消息通知
         * */
     /*   QueryWrapper<HkAssessmentScore> query1 = Wrappers.query();
        query1.like(HkAssessmentScore.PROCESS_INSTANCE_ID, score.getProcessInstanceId());
        List<HkAssessmentScore> hkAssessmentScores = hkAssessmentScoreMapper.selectList(query1);
        String hontUserId = hkAssessmentScores.get(0).getHontUserId();
        List<String> openIdByUserIn = hontUserMapper.getOpenIdByUserIn(hontUserId);
        if(openIdByUserIn.size()>0){
            String[] array=new String[openIdByUserIn.size()];
            for(int i=0;i<openIdByUserIn.size();i++){
                array[i]=openIdByUserIn.get(i);
            }
            feignInterface.end(array);
        }*/
    }
    /*
     *
     * */

    @Override
    public List<HkAssessmentScore> getHkAssessmentScoreByProIds(List<String> ids) {
        HontUserTo hontUserTo = feignInterface.remoteUserInfo();
        QueryWrapper<HkAssessmentScore> query = Wrappers.query();
        query.in(HkAssessmentScore.PROCESS_INSTANCE_ID, ids);
        query.eq(HkAssessmentScore.IS_CURRENT_ASSESSMENT, "1");
        List<HkAssessmentScore> hkAssessmentScores = hkAssessmentScoreMapper.selectList(query);
       /* for(int i=0;i<hkAssessmentScores.length;i++){
        }*/

        return hkAssessmentScores;
    }

    /**
     * 功能描述:
     * 待办列表
     *
     * @return: java.util.List<com.hkts.naturalgas.performance.performanceVo.PerformanceInfoNameAndUserNickVo>
     * @Author: 杨春科
     * @Date: 22/9/2022 下午3:13
     * @Description //TODO
     */
    @Override
    public Result<LinkedHashMap<String, List<PerformanceInfoNameAndUserNickVo>>> getHkAssessmentInfoAndUserNickNameByProIds() {
        HontUserTo hontUserTo = feignInterface.remoteUserInfo();
        List<String> dealtWith = iHkAssessmentInfoService.getDealtWith(hontUserTo.getId());
        log.info("待办列表：{}", dealtWith);
        if (dealtWith.size() == 0) {
            Result<LinkedHashMap<String, List<PerformanceInfoNameAndUserNickVo>>> data = ResultUtil.data(null);
            data.setMessage(0 + "");
            return data;

        }
        List<PerformanceInfoNameAndUserNickVo> hkAssessmentInfoAndUserNickNameByProIds1 = hkAssessmentScoreMapper.getHkAssessmentInfoAndUserNickNameByProIds(dealtWith);
        Iterator<PerformanceInfoNameAndUserNickVo> iterator1 = hkAssessmentInfoAndUserNickNameByProIds1.iterator();
        //过滤重复得数据
        List<String> empProcess = new ArrayList<String>();
        while (iterator1.hasNext()) {
            PerformanceInfoNameAndUserNickVo next = iterator1.next();
            if (empProcess.contains(next.getProcessInstanceId())) {
                iterator1.remove();
            } else {
                empProcess.add(next.getProcessInstanceId());
            }
        }
        LinkedHashMap<String, List<PerformanceInfoNameAndUserNickVo>> lingkmap = new LinkedHashMap<>();
        SimpleDateFormat formatemd = new SimpleDateFormat("MM月dd日");

        for (int i = 0; i < hkAssessmentInfoAndUserNickNameByProIds1.size(); i++) {
            if (lingkmap.containsKey(hkAssessmentInfoAndUserNickNameByProIds1.get(i).getCreateTime())) {
                for (int j = 0; j < dealtWith.size(); j++) {
                    if (dealtWith.get(j).equals(hkAssessmentInfoAndUserNickNameByProIds1.get(i).getProcessInstanceId())) {
                        hkAssessmentInfoAndUserNickNameByProIds1.get(i).setTaskId(dealtWith.get(j));
                        lingkmap.get(hkAssessmentInfoAndUserNickNameByProIds1.get(i).getCreateTime()).add(hkAssessmentInfoAndUserNickNameByProIds1.get(i));
                        break;
                    }
                }
            } else {
                for (int j = 0; j < dealtWith.size(); j++) {
                    if (dealtWith.get(j).equals(hkAssessmentInfoAndUserNickNameByProIds1.get(i).getProcessInstanceId())) {
                        List<PerformanceInfoNameAndUserNickVo> hkAssessmentInfoAndUserNickNameByProIds2 = new ArrayList<PerformanceInfoNameAndUserNickVo>();
                        hkAssessmentInfoAndUserNickNameByProIds1.get(i).setTaskId(dealtWith.get(j));
                        hkAssessmentInfoAndUserNickNameByProIds2.add(hkAssessmentInfoAndUserNickNameByProIds1.get(i));
                        lingkmap.put(hkAssessmentInfoAndUserNickNameByProIds1.get(i).getCreateTime(), hkAssessmentInfoAndUserNickNameByProIds2);
                        break;
                    }
                }
            }
        }
        // List<PerformanceInfoNameAndUserNickVo> hkAssessmentInfoAndUserNickNameByProIds = feignPerformance.getHkAssessmentInfoAndUserNickNameByProIds(proessId);
        Result<LinkedHashMap<String, List<PerformanceInfoNameAndUserNickVo>>> data = ResultUtil.data(lingkmap);
        data.setMessage(dealtWith.size() + "");
        return data;
    }

    @Override
    public List<PerformanceScoreListVo> getHkAssessmentScoreByProId(String proessId) {
        List<PerformanceScoreListVo> list = hkAssessmentScoreMapper.getHkAssessmentScoreByProId(proessId);
        /*
         * YCK修改
         * */
        list.stream().forEach(vo -> {
            QueryWrapper<HkAssessmentPicture> query = Wrappers.query();
            QueryWrapper<HkAssessmentPicture> eq = query.eq(HkAssessmentPicture.PROCESS_INSTANCE_ID, vo.getProcessInstanceId())
                    .eq(HkAssessmentPicture.INDEX_ID, vo.getIndexId());
            List<HkAssessmentPicture> hkAssessmentPictures = hkAssessmentPictureMapper.selectList(eq);
            List<String> imgList = hkAssessmentPictures.stream().map(HkAssessmentPicture::getPictureUrl).collect(Collectors.toList());
            vo.setImgList(imgList);
        });

        return list;
    }

    /*
     * 修改后再通过
     *
     * */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> approvalWithoutScore(String processInstanceId, String taskId) throws Exception {
        log.info("审核参数processId：{}", processInstanceId + "," + taskId);
        HontUserTo hontUserTo = feignInterface.remoteUserInfo();
        QueryWrapper<HkAssessmentScore> query = Wrappers.query();
        query.eq(HkAssessmentScore.PROCESS_INSTANCE_ID, processInstanceId);
        query.eq(HkAssessmentScore.IS_CURRENT_ASSESSMENT, "1");
        List<HkAssessmentScore> hkAssessmentScores = hkAssessmentScoreMapper.selectList(query);

        Result<Object> approval1 = iFlowTaskInstanceService.approval(processInstanceId);
        boolean approval = false;
        if (approval1.getCode() == 500) {
            throw new Exception("您没有权限审批此节点");
        } else {
            approval = (boolean) approval1.getResult();
        }
        /*String pt = processInstanceId + "," + taskId;
        System.out.println("pt:" + pt);
        String s = feignFlow.completePerformance(pt);
        if (s.equals("101")) {
            //没有此任务，请确认!
            throw new Exception("该待办已经被其他用户审核！");
        } else if (s.equals("500")) {
            throw new Exception("流程挂起，请联系管理员激活后再操作！");
        } else if (!s.equals("100")) {
            throw new Exception("网络配置异常，请联系管理员处理！");
        }*/

        Result<Map<String, Object>> result = feignInterface.performanceUserInfo();
        Map<String, Object> result1 = result.getResult();
        String identity = result1.get("identity").toString();
        LocalDateTime now = LocalDateTime.now();
        HkAssessmentScore ss = new HkAssessmentScore();
        ss.setProcessInstanceId(processInstanceId);
        ss.setIsCurrentAssessment("2");
        hkAssessmentScoreMapper.updateIsCurrentByProcessInstanceId(ss);

        /*
         * 修改performanceInfo
         * */
        QueryWrapper<HkAssessmentInfo> queryInfo = Wrappers.query();
        queryInfo.eq("process_instance_id", processInstanceId);
        List<HkAssessmentInfo> hkAssessmentInfos = hkAssessmentInfoMapper.selectList(queryInfo);
        HkAssessmentInfo hkAssessmentInfo = hkAssessmentInfos.get(0);
        HontUser hontUser = hontUserMapper.selectById(hkAssessmentScores.get(0).getHontUserId());
        DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
        String format = dtf2.format(hkAssessmentInfo.getCreateTime());

        hkAssessmentInfo.setAssessmentName(hontUserTo.getNickName() + "审核了" + hontUser.getNickName() + format + "绩效考核");
        if (approval) {
            hkAssessmentInfo.setAssessmentStatus("2");
            hkAssessmentInfo.setEndTime(LocalDateTime.now());
        }
        hkAssessmentInfoMapper.update(hkAssessmentInfo, queryInfo);

        /* 重新保存分数记录 ------------*/
        for (int i = 0; i < hkAssessmentScores.size(); i++) {
            HkAssessmentScore score = new HkAssessmentScore();
            score.setIndexName(hkAssessmentScores.get(i).getIndexName());
            /*score.setTxtId(hkAssessmentScores.get(i).getTxtId());
            score.setNumId(hkAssessmentScores.get(i).getNumId());*/
            score.setIsCurrentAssessment(hkAssessmentScores.get(i).getIsCurrentAssessment());
            score.setProcessInstanceId(hkAssessmentScores.get(i).getProcessInstanceId());
            score.setScore(hkAssessmentScores.get(i).getScore());
            score.setCreateTime(now);
            score.setRoleLevel(identity);
            score.setIndexDescribe(hkAssessmentScores.get(i).getIndexDescribe());
            score.setIndexId(hkAssessmentScores.get(i).getIndexId());
            score.setId(IDUtils.genImageName());
            score.setHontUserId(hkAssessmentScores.get(i).getHontUserId());
            score.setApprovalUserId(hontUserTo.getId());
            score.setScoreType(hkAssessmentScores.get(i).getScoreType());
            if (approval) {
                score.setScoreState("2");
            } else {
                score.setScoreState("1");
            }

            score.setIndexComment(PerformanceConstant.AGREE);
            score.setIndexFrequency(hkAssessmentScores.get(i).getIndexFrequency());
            hkAssessmentScoreMapper.insert(score);
        }
        /*
         * 业务执行成功后用来判断是否需要发送消息
         * */
        if (approval) {
            sendMessage(hontUser.getId());
        }
        //回调需要处理待办得流程id和任务id
        /*
         * 查找下一个待办
         * */
        Map<String, Object> map = new HashMap<String, Object>();
        List<FlowInstanceinfo> copy = flowInstanceinfoMapper.getBackLog(hontUserTo.getId(),"1");
        log.info("下一个待办：{}", copy);
        if (copy.size() > 0) {
            map.put("processInstanceId", copy.get(0).getId());
            map.put("taskId", copy.get(0).getId());
        } else {
            return null;
        }
        return map;
    }
    public ParamVo getDateTime(ParamVo param){

        switch(param.getSelectType()){
            case ParamVo.day: {
                param.setBeginDate(DateUtils.getCurrentDate() + " 00:00:00");
                param.setEndDate(DateUtils.getCurrentDate() + " 23:59:59");
                return param;
            }
            case ParamVo.yesterday:{
                param.setBeginDate(DateUtils.getFrontDate() + " 00:00:00");
                param.setEndDate(DateUtils.getFrontDate() + " 23:59:59");
                return param;
            }
            case ParamVo.week: {
                param.setBeginDate( DateUtils.getCurrentWeekFirstDate().format(DateTimeFormatter.ofPattern(DateUtils.DATE_FORMATTER))+ " 00:00:00");
                param.setEndDate(DateUtils.getCurrentWeekLastDate().format(DateTimeFormatter.ofPattern(DateUtils.DATE_FORMATTER))+ " 23:59:59");
                return param;
            }
            case ParamVo.month: {
                param.setBeginDate( DateUtils.getCurrentMonthFirstDate().format(DateTimeFormatter.ofPattern(DateUtils.DATE_FORMATTER))+ " 00:00:00");
                param.setEndDate( DateUtils.getCurrentMonthLastDate().format(DateTimeFormatter.ofPattern(DateUtils.DATE_FORMATTER))+ " 23:59:59");
                return param;
            }
            default: {
                param.setBeginDate(param.getBeginDate()+ " 00:00:00");
                param.setEndDate(param.getEndDate()+ " 23:59:59");
                return param;
            }
        }
    }
    @Override
    /**
     * 今天与本月总加分数
     */
    public Map<String, Object> selectScoreByHontUserOnDepartementPositive() {

        String id = feignInterface.remoteUserInfo().getId();
        HontUserRole hontRole = hontUserRoleMapper.getByUserId(id);
        HontRole hontRoleByUser = hontRoleMapper.selectById(hontRole.getHontRoleId());

        List<String> departmentIds = feignInterface.getDepartmentIds();
        Map<String, Object> resultMap = new HashMap<>();
        ParamVo paramVo = new ParamVo();
        paramVo.setSelectType(0);
        ParamVo dateTime = getDateTime(paramVo);
        //今天加减分
        //List<String> dateArrayToday = DateUtil.getDateArray("today", "", "");
        Map<String, Integer> stringIntegerMapPositive =
                hkAssessmentScoreMapper.selectScoreByHontUserOnDepartementPositive(dateTime.getBeginDate(),dateTime.getEndDate(),
                        departmentIds, id);
        //个人本月累计
        ParamVo paramVoMonth = new ParamVo();
        paramVoMonth.setSelectType(3);
        ParamVo month = getDateTime(paramVoMonth);
        QueryWrapper<FlowInstanceinfo> query = Wrappers.query();
        query.lambda().eq(FlowInstanceinfo::getHontUserId,id)
                .eq(FlowInstanceinfo::getFlowStatus,1);
        query.lambda().apply(StringUtils.isNotBlank(month.beginDate),
                "date_format (flow_create_time,'%Y-%m-%d %H:%i:%s') >= date_format('" + month.beginDate + "','%Y-%m-%d %H:%i:%s')")
                .apply(StringUtils.isNotBlank(month.endDate),
                        "date_format (flow_create_time,'%Y-%m-%d %H:%i:%s') <= date_format('" + month.endDate + "','%Y-%m-%d %H:%i:%s')");
        Integer integer = flowInstanceinfoMapper.selectCount(query);
        Integer performanceByDepartment = 0;
        Integer performanceByDepartmentTo = 0;
        String bottomAvgByDepartment = "0";
        if (departmentIds.size() > 0 ){
            //班长及以上权限的本月累计
            performanceByDepartment = flowInstanceinfoMapper.getPerformanceByDepartment(departmentIds, month.getBeginDate(),month.getEndDate());
            //主管主任等角色的日累计
            performanceByDepartmentTo = flowInstanceinfoMapper.getPerformanceByDepartment(departmentIds, dateTime.getBeginDate(),dateTime.getEndDate());
            //主管主任等角色审批月均用时
            bottomAvgByDepartment = flowInstanceinfoMapper.getBottomAvgByDepartment(departmentIds, month.getBeginDate(),month.getEndDate());

        }

        if (hontRoleByUser.getLevel() < 3){
            if (stringIntegerMapPositive == null) {
                resultMap.put("positive", 0);
                resultMap.put("minus", 0);
            } else {
                resultMap.put("positive", stringIntegerMapPositive.get("Sum1"));
                resultMap.put("minus", stringIntegerMapPositive.get("Sum2"));
            }
        }else if (hontRoleByUser.getLevel() >= 3 && hontRoleByUser.getLevel() < 6){

            resultMap.put("positive", performanceByDepartmentTo);
            if (StringUtils.isNotBlank(bottomAvgByDepartment)){
                resultMap.put("minus", bottomAvgByDepartment);
            }else {
                resultMap.put("minus", 0);
            }
        }else if (hontRoleByUser.getLevel() == 6){
            ParamVo indexParamVo = new ParamVo();
            Result<Object> objectResult = indexService.countIndex(indexParamVo);
            Map map = BeanConvertUtils.objectToMap(objectResult.getResult());

            resultMap.put("positive", map.get("hontLog"));
            resultMap.put("minus", map.get("countInstanceinfo"));
            resultMap.put("size", map.get("countInstanceinfoMouth"));
        }
        if (hontRoleByUser.getLevel() < 2) {
            resultMap.put("size", integer);
        }else if (hontRoleByUser.getLevel() >= 2 && hontRoleByUser.getLevel() < 6){
            resultMap.put("size", performanceByDepartment);
        }

        return resultMap;
    }

    @Override
    public Map<String, Object> selectHistoryByProcessId(String processId) {
        List<Map<String, Object>> maps = hkAssessmentScoreMapper.selectHistoryByProcessId(processId);
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Integer> scores = new HashMap<>();
        int score = 0;
        for (int i = 0; i < maps.size(); i++) {
            String scorestring = String.valueOf(maps.get(i).get("score"));
            score = Integer.parseInt(scorestring) + score;
            scores.put("scores", score);
            resultMap.put("scores", scores);
        }
        resultMap.put("particulars", maps);

        return resultMap;
    }

    @Override
    public CustomPage selectHistoryByHontUser(CustomPage page) throws ParseException {
        HontUserTo hontUserTo = feignInterface.remoteUserInfo();
        AssessmentHontUserQueryVo assessmentHontUserQueryVo = new AssessmentHontUserQueryVo();
        assessmentHontUserQueryVo.setUserId(hontUserTo.getId());
        assessmentHontUserQueryVo.setFirstRow(page.getFirstRow());
        assessmentHontUserQueryVo.setLastRow(page.getLastRow());
        List<Map<String, Object>> maps = hkAssessmentScoreMapper.selectHistoryByHontUserCount(assessmentHontUserQueryVo);
        List<Map<String, Object>> monthMaps = hkAssessmentScoreMapper.selectHistoryByHontUserAndTime(assessmentHontUserQueryVo);
        Map<String, List<Map<String, Object>>> resultMap = new HashMap<>();

        if (maps.size() > 0) {
            for (int i = 0; i < maps.size(); i++) {
                List<Map<String, Object>> mapList = new ArrayList<>();
                String time = maps.get(i).get("time").toString();
                Date date = DateUtil.StrToDate(time + "-01");
                Calendar cal = Calendar.getInstance();
                cal.setTime(date);
                int months = cal.get(Calendar.MONTH) + 1;
                int year = cal.get(Calendar.YEAR);
                for (int j = 0; j < monthMaps.size(); j++) {
                    Map<String, Object> map = new HashMap<>();
                    String dateA = monthMaps.get(j).get("time").toString();
                    map.put("pid", monthMaps.get(j).get("pid"));
                    map.put("nickName", monthMaps.get(j).get("nick_name"));
                    map.put("score", monthMaps.get(j).get("score"));
                    map.put("time", monthMaps.get(j).get("time"));
                    map.put("status", monthMaps.get(j).get("status"));
                    Date timeTo = DateUtil.StrToDate(dateA);
                    cal.setTime(timeTo);
                    int monthTo = cal.get(Calendar.MONTH) + 1;
                    if (months == monthTo) {
                        mapList.add(map);
                    }
                }
                resultMap.put(year + "年" + months + "月", mapList);
            }
        }

        page.setResultData(resultMap);
        page.setTotalRows((long) maps.size());
        return page;
    }

    /**
     * 审核提交 v1.5
     *
     * @param submitPerformanceDTo
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> approvalWithScoreVf(SubmitPerformanceDTo submitPerformanceDTo) throws Exception {
        HontUserTo hontUserTo = feignInterface.remoteUserInfo();
        LocalDateTime now = LocalDateTime.now();
        long start = System.currentTimeMillis();
// some code


        Result<Object> approval1 = iFlowTaskInstanceService.approval(submitPerformanceDTo.getProcessInstanceId());
        boolean approval = false;
        if (approval1.getCode() == 500) {
            throw new Exception("您没有权限审批此节点");
        } else {
            approval = (boolean) approval1.getResult();
        }
        long finish = System.currentTimeMillis();
        long timeElapsed = finish - start;
        log.info("接口调用耗时：{}", timeElapsed);
        /*
         * 修改performanceInfo
         * */
        QueryWrapper<HkAssessmentInfo> query = Wrappers.query();
        query.eq("process_instance_id", submitPerformanceDTo.getProcessInstanceId());
        List<HkAssessmentInfo> hkAssessmentInfos = hkAssessmentInfoMapper.selectList(query);
        HkAssessmentInfo hkAssessmentInfo = hkAssessmentInfos.get(0);
        QueryWrapper<HkAssessmentScore> queryHistory = Wrappers.query();
        queryHistory.eq("process_instance_id", submitPerformanceDTo.getProcessInstanceId());
        List<HkAssessmentScore> hkAssessmentScores = hkAssessmentScoreMapper.selectList(queryHistory);
        String hontUserId = hkAssessmentScores.get(0).getHontUserId();

        List<String> scoreIds = new ArrayList<String>();
        hkAssessmentScores.stream().forEach(hkAssessmentScore -> {
            scoreIds.add(hkAssessmentScore.getIndexId());
        });

        HontUser hontUser = hontUserMapper.selectById(hontUserId);
        /*
         * 时间格式化
         * */
        DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
        String format = dtf2.format(hkAssessmentInfo.getCreateTime());
        hkAssessmentInfo.setAssessmentName(hontUserTo.getNickName() + "审核了" + hontUser.getNickName() + format + "绩效考核");
        if (approval) {
            hkAssessmentInfo.setAssessmentStatus("2");
            hkAssessmentInfo.setEndTime(LocalDateTime.now());
        }
        //设置修改范围
        QueryWrapper<HkAssessmentInfo> updateInfoHistory = Wrappers.query();
        updateInfoHistory.eq(HkAssessmentInfo.PROCESS_INSTANCE_ID, submitPerformanceDTo.getProcessInstanceId());

        HkAssessmentScore ss = new HkAssessmentScore();
        ss.setProcessInstanceId(submitPerformanceDTo.getProcessInstanceId());
        ss.setIsCurrentAssessment("2");
        hkAssessmentScoreMapper.updateIsCurrentByProcessInstanceId(ss);


        List<IndexAndFormIdVo> listContent = submitPerformanceDTo.getList();
        /*
         * 判断是否有加分或减分的item
         * 如果没有 将所有项目存储
         * 如果有----只将变化数据进行持久话
         * */

        Float score1 = (float) 0;
        /*
         * 将分数持久化到数据库
         * */
        first:
        for (int i = 0; i < listContent.size(); i++) {
            HkAssessmentScore score = new HkAssessmentScore();
            /*
             * 如果有评分项时将没有评分项进行过滤
             * */
            if (!scoreIds.contains(listContent.get(i).getIndexId()) && (listContent.get(i).getIndexFrequency() == null || listContent.get(i).getIndexFrequency().toString().equals("") || listContent.get(i).getIndexFrequency().toString().equals("0.0") || listContent.get(i).getIndexFrequency() == 0)) {
                System.out.println("continue");
                continue first;
            }
            if (listContent.get(i).getIndexType() == 2) {
                score.setIndexFrequency((int) Float.parseFloat(listContent.get(i).getIndexFrequency().toString()));
                if (StringUtils.isNotBlank(listContent.get(i).getScoreType()) && listContent.get(i).getScoreType().equals(HkAssessmentIndex.SCORE_TYPE_DELETE)) {
                    score.setScore(Float.parseFloat(listContent.get(i).getIndexFrequency().toString()));
                } else if (StringUtils.isNotBlank(listContent.get(i).getScoreType()) && listContent.get(i).getScoreType().equals(HkAssessmentIndex.SCORE_TYPE_ADD)) {
                    score.setScore(Float.parseFloat(listContent.get(i).getIndexFrequency().toString()));
                }
            } else if (listContent.get(i).getIndexType() == 3) {
                score.setScore(Float.parseFloat(listContent.get(i).getIndexFrequency().toString()));
                score.setIndexFrequency((int) Float.parseFloat(listContent.get(i).getIndexFrequency().toString()));
            } else if (listContent.get(i).getIndexType() == 4) {
                score.setScore(-Float.parseFloat(listContent.get(i).getIndexFrequency().toString()));
                score.setIndexFrequency((int) Float.parseFloat(listContent.get(i).getIndexFrequency().toString()));
            } else {
                score.setScore(Float.parseFloat(listContent.get(i).getIndexFrequency().toString()) * Float.parseFloat(listContent.get(i).getIndexScore().toString()));
                score.setIndexFrequency((int) Float.parseFloat(listContent.get(i).getIndexFrequency().toString()));
            }
            score.setIndexDescribe(listContent.get(i).getIndexDescribe());
            score.setIndexName(listContent.get(i).getIndexName());
            score.setScoreType(listContent.get(i).getScoreType());
            score.setApprovalUserId(hontUserTo.getId());
            score.setHontUserId(submitPerformanceDTo.getHontUserId());
            score.setId(IDUtils.genImageName());
            score.setIndexId(listContent.get(i).getIndexId());
            if (approval) {
                score.setScoreState("2");
            } else {
                score.setScoreState("1");
            }
            //处理评论问题
            if (listContent.get(i).getIndexComment() != null) {
                //将所有历史记录进行查询，如果包含相同评论则不持久话该评论
                QueryWrapper<HkAssessmentScore> commentQuery = Wrappers.query();
                commentQuery.eq("process_instance_id", submitPerformanceDTo.getProcessInstanceId());
                commentQuery.eq("index_id", listContent.get(i).getIndexId());
                //
                String indexComment = listContent.get(i).getIndexComment();
                List<HkAssessmentScore> hkAssessmentScores1 = hkAssessmentScoreMapper.selectList(commentQuery);
                if (hkAssessmentScores1.size() > 0) {
                    //通过标识判断
                    boolean bs = false;
                    for (int j = 0; j < hkAssessmentScores1.size(); j++) {
                        if (hkAssessmentScores1.get(j).getIndexComment() != null && hkAssessmentScores1.get(j).getIndexComment().equals(indexComment)) {
                            bs = true;
                            break;
                        }
                    }
                    if (!bs) {
                        score.setIndexComment(listContent.get(i).getIndexComment());
                    } else {
                        score.setIndexComment(PerformanceConstant.AGREE);
                    }

                } else {
                    score.setIndexComment(listContent.get(i).getIndexComment());
                }
            }
            /*
             *处理图片数据
             * */
            if (listContent.get(i).getImglist().size() > 0) {
                // String imgList = list.get(i).get("imgList").toString();
                List imgList = listContent.get(i).getImglist();
                iHkAssessmentPictureService.updateImageByProcessAndItem(submitPerformanceDTo.getProcessInstanceId(), score.getIndexId(), imgList);
            }
            score.setCreateTime(now);
            score.setIsCurrentAssessment("1");
            score.setProcessInstanceId(submitPerformanceDTo.getProcessInstanceId());
            hkAssessmentScoreMapper.insert(score);
            score1 += score.getScore();
        }
        hkAssessmentInfo.setAssessmentScore(score1);
        hkAssessmentInfoMapper.update(hkAssessmentInfo, updateInfoHistory);
        /*
         * 业务执行成功后用来判断是否需要发送消息
         * */
        if (approval) {
            sendMessage(hontUser.getId());
        }
        /*
         * 查找下一个待办
         * */
        Map<String, Object> map = new HashMap<String, Object>();
        List<FlowInstanceinfo> copy = flowInstanceinfoMapper.getBackLog(hontUserTo.getId(),"1");
        if (copy.size() > 0) {
            map.put("processInstanceId", copy.get(0).getId());
            map.put("taskId", copy.get(0).getId());
        } else {
            return null;
        }
        return map;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> approvalWithScore(String list, String processInstanceId, String taskId) throws Exception {
        HontUserTo hontUserTo = feignInterface.remoteUserInfo();
        Gson gson = new Gson();
        List<Map<String, Object>> listVo = new ArrayList<Map<String, Object>>();
        Result<Map<String, Object>> result = feignInterface.performanceUserInfo();
        Map<String, Object> result1 = result.getResult();
        String identity = result1.get("identity").toString();
        LocalDateTime now = LocalDateTime.now();
        String s = feignFlow.completePerformance(processInstanceId + "," + taskId);
        if (s.equals("101")) {
            //没有此任务，请确认!
            throw new Exception("该流程已经被其他用户审批！");
        } else if (s.equals("500")) {
            throw new Exception("流程挂起，请联系管理员激活后再操作！");
        } else if (!s.equals("100")) {
            throw new Exception("网络配置异常，请联系管理员处理！");
        }
        /*
         * 修改performanceInfo
         * */
        QueryWrapper<HkAssessmentInfo> query = Wrappers.query();
        query.eq("process_instance_id", processInstanceId);
        List<HkAssessmentInfo> hkAssessmentInfos = hkAssessmentInfoMapper.selectList(query);
        HkAssessmentInfo hkAssessmentInfo = hkAssessmentInfos.get(0);
        QueryWrapper<HkAssessmentScore> queryHistory = Wrappers.query();
        queryHistory.eq("process_instance_id", processInstanceId);
        List<HkAssessmentScore> hkAssessmentScores = hkAssessmentScoreMapper.selectList(queryHistory);
        String hontUserId = hkAssessmentScores.get(0).getHontUserId();
        List<Map<String, Object>> listContent = gson.fromJson(list, listVo.getClass());
        HontUser hontUser = hontUserMapper.selectById(hontUserId);
        /*
         * 时间格式化
         * */
        DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
        String format = dtf2.format(hkAssessmentInfo.getCreateTime());
        hkAssessmentInfo.setAssessmentName(hontUserTo.getNickName() + "审核了" + hontUser.getNickName() + format + "绩效考核");
        if (identity.equals("5")) {
            hkAssessmentInfo.setAssessmentStatus("2");
        }
        //设置修改范围
        QueryWrapper<HkAssessmentInfo> updateInfoHistory = Wrappers.query();
        updateInfoHistory.eq(HkAssessmentInfo.PROCESS_INSTANCE_ID, processInstanceId);

        HkAssessmentScore ss = new HkAssessmentScore();
        ss.setProcessInstanceId(processInstanceId);
        ss.setIsCurrentAssessment("2");
        hkAssessmentScoreMapper.updateIsCurrentByProcessInstanceId(ss);
        hkAssessmentInfoMapper.update(hkAssessmentInfo, updateInfoHistory);
        /*
         * 判断是否有加分或减分的item
         * 如果没有 将所有项目存储
         * 如果有----只将变化数据进行持久话
         * */
        boolean flag = false;

        for (int i = 0; i < listContent.size(); i++) {
            if (listContent.get(i).get("indexFrequency") != null && !listContent.get(i).get("indexFrequency").toString().equals("") && !listContent.get(i).get("indexFrequency").toString().equals("0.0")) {
                flag = true;
                break;
            }
        }
        /*
         * 将分数持久化到数据库
         * */
        first:
        for (int i = 0; i < listContent.size(); i++) {
            HkAssessmentScore score = new HkAssessmentScore();
            /*
             * 如果有评分项时将没有评分项进行过滤
             * */
            if (flag && (listContent.get(i).get("indexFrequency") == null || listContent.get(i).get("indexFrequency").toString().equals("") || listContent.get(i).get("indexFrequency").toString().equals("0.0"))) {
                System.out.println("continue");
                continue first;
            } else {
                System.out.println("indexFrequency:" + listContent.get(i).get("indexFrequency"));
            }
            if (listContent.get(i).get("indexId").toString().equals(PerformanceConstant.IS_CUSTOM_DELETE)) {
                score.setScore(-Float.parseFloat(listContent.get(i).get("indexFrequency").toString()));
                score.setIndexFrequency((int) Float.parseFloat(listContent.get(i).get("indexFrequency").toString()));
                if (listContent.get(i).get("indexComment") != null) {
                    score.setIndexComment(listContent.get(i).get("indexComment").toString());
                    score.setIndexDescribe(listContent.get(i).get("indexComment").toString());
                }
                score.setIndexName("自定义减分项");
            } else if (listContent.get(i).get("indexId").toString().equals(PerformanceConstant.IS_CUSTOM_ADD)) {
                score.setScore(Float.parseFloat(listContent.get(i).get("indexFrequency").toString()));
                score.setIndexFrequency((int) Float.parseFloat(listContent.get(i).get("indexFrequency").toString()));
                if (listContent.get(i).get("indexComment") != null) {
                    score.setIndexComment(listContent.get(i).get("indexComment").toString());
                    score.setIndexDescribe(listContent.get(i).get("indexComment").toString());
                }
                score.setIndexName("自定义加分项");
            } else {
                score.setIndexDescribe(listContent.get(i).get("indexDescribe").toString());
                score.setIndexFrequency((int) Float.parseFloat(listContent.get(i).get("indexFrequency").toString()));
                score.setIndexName(listContent.get(i).get("indexName").toString());
                HkAssessmentIndex indexId = hkAssessmentIndexMapper.selectById(listContent.get(i).get("indexId").toString());
                float v = indexId.getIndexScore().floatValue();
                score.setScore(Float.parseFloat(listContent.get(i).get("indexFrequency").toString()) * v);
            }
            score.setApprovalUserId(hontUserTo.getId());
            score.setHontUserId(hontUser.getId());
            score.setId(IDUtils.genImageName());
            score.setIndexId(listContent.get(i).get("indexId").toString());
            if (identity.equals("5")) {
                score.setScoreState("2");
            } else {
                score.setScoreState("1");
            }
            //处理评论问题
            if (listContent.get(i).get("indexComment") != null) {
                //将所有历史记录进行查询，如果包含相同评论则不持久话该评论
                QueryWrapper<HkAssessmentScore> commentQuery = Wrappers.query();
                commentQuery.eq("process_instance_id", processInstanceId);
                commentQuery.eq("index_id", listContent.get(i).get("indexId").toString());
                //
                String indexComment = listContent.get(i).get("indexComment").toString();
                List<HkAssessmentScore> hkAssessmentScores1 = hkAssessmentScoreMapper.selectList(commentQuery);
                if (hkAssessmentScores1.size() > 0) {
                    //通过标识判断
                    boolean bs = false;
                    for (int j = 0; j < hkAssessmentScores1.size(); j++) {
                        if (hkAssessmentScores1.get(j).getIndexComment() != null && hkAssessmentScores1.get(j).getIndexComment().equals(indexComment)) {
                            bs = true;
                            break;
                        }
                    }
                    if (!bs) {
                        score.setIndexComment(listContent.get(i).get("indexComment").toString());
                    } else {
                        score.setIndexComment(PerformanceConstant.AGREE);
                    }

                } else {
                    score.setIndexComment(listContent.get(i).get("indexComment").toString());
                }
            }
            /*
             *处理图片数据
             * */
            if (listContent.get(i).get("imgList") != null) {
                // String imgList = list.get(i).get("imgList").toString();
                List imgList = (List) listContent.get(i).get("imgList");
                iHkAssessmentPictureService.updateImageByProcessAndItem(processInstanceId, score.getIndexId(), imgList);
            }
            score.setCreateTime(now);
            score.setIsCurrentAssessment("1");
            score.setRoleLevel(identity);
            score.setNumId(listContent.get(i).get("numId").toString());
            score.setTxtId(listContent.get(i).get("txtId").toString());
            score.setProcessInstanceId(processInstanceId);
            hkAssessmentScoreMapper.insert(score);
        }
        /*
         * 业务执行成功后用来判断是否需要发送消息
         * */
        if (identity.equals("5")) {
            sendMessage(hontUser.getId());
        }
        /*
         * 查找下一个待办
         * */
        Map<String, Object> map = new HashMap<String, Object>();
        String perPormanceByPerPormance = feignFlow.getPerPormanceByPerPormance();
        System.out.println("perPormanceByPerPormance:" + perPormanceByPerPormance);
        if (perPormanceByPerPormance == null || perPormanceByPerPormance.equals("500")) {
            return null;
        } else {
            String[] split = perPormanceByPerPormance.split(",");
            map.put("processInstanceId", split[0]);
            map.put("taskId", split[1]);
        }
        return map;
    }

    @Override
    public List<HistoryCommentAndScoreVo> getHistoryCommentAndScore(String processInstanceId, String indexId) {
        QueryWrapper<HkAssessmentScore> query = Wrappers.query();
        query.eq(HkAssessmentScore.PROCESS_INSTANCE_ID, processInstanceId);
        query.eq(HkAssessmentScore.INDEX_ID, indexId);
        query.orderByAsc(HkAssessmentScore.ROLE_LEVEL);
        List<HkAssessmentScore> hkAssessmentScores = hkAssessmentScoreMapper.selectList(query);
        List<HistoryCommentAndScoreVo> voList = new ArrayList<>();
        hkAssessmentScores.stream().forEach(hkAssessmentScore -> {
            HistoryCommentAndScoreVo vo = new HistoryCommentAndScoreVo();
            vo.setComment(hkAssessmentScore.getIndexComment());
            vo.setScore(hkAssessmentScore.getScore());
            HontUser hontUser = hontUserMapper.selectById(hkAssessmentScore.getApprovalUserId());
            vo.setNickName(hontUser.getNickName());
            voList.add(vo);
        });
        return voList;
    }


    //用于远程调用结束通知

    public void sendMessage(String hontUserId) {
        /*
         * 远程调用消息通知
         * */
        List<String> openIdByUserIn = hontUserMapper.getOpenIdByUserIn(hontUserId);
        if (openIdByUserIn.size() > 0) {
            String[] array = new String[openIdByUserIn.size()];
            for (int i = 0; i < openIdByUserIn.size(); i++) {
                array[i] = openIdByUserIn.get(i);
            }
            feignInterface.end(array);
        }
    }
    /**
     * 根据时间查询人员、班组、全部班组的考核记录（分页）
     * @param page
     * @param paramVo
     * @return
     */
    @Override
    public Page getPersonPerformanceByDate(CustomPage page,ParamVo paramVo){

        ParamVo dateTime = getDateTime(paramVo);
        List<String> departmentIds = feignInterface.getDepartmentIds();
        HontUserTo hontUserTo = feignInterface.remoteUserInfo();
        String id = hontUserTo.getId();
        //获取所有待办process-task  id
        //String listApplyedTasks = feignFlow.getListApplyedTasks("");
        List<String> processIds = iHkAssessmentInfoService.getDealtWith(id);
        if (paramVo.getDepartType() == 0){
            QueryWrapper<HkAssessmentInfo> query = Wrappers.query();
            query.lambda().eq(HkAssessmentInfo::getHontUserId,id)
                    .eq(HkAssessmentInfo::getAssessmentStatus,2);
            query.lambda().apply(StringUtils.isNotBlank(dateTime.beginDate),
                    "date_format (create_time,'%Y-%m-%d %H:%i:%s') >= date_format('" + dateTime.beginDate + "','%Y-%m-%d %H:%i:%s')")
                    .apply(StringUtils.isNotBlank(dateTime.endDate),
                            "date_format (create_time,'%Y-%m-%d %H:%i:%s') <= date_format('" + dateTime.endDate + "','%Y-%m-%d %H:%i:%s')");
            List<HkAssessmentInfo> hkAssessmentInfos = hkAssessmentInfoMapper.selectList(query);
            List<String> scoreIds = new ArrayList<String>();
            hkAssessmentInfos.stream().forEach(hkAssessmentDetailVo -> {
                scoreIds.add(hkAssessmentDetailVo.getProcessInstanceId());

            });
            if (scoreIds.size() < 1){
                return new Page<HkAssessmentScore>();
            }
            QueryWrapper<HkAssessmentScore> scoreQueryWrapper = Wrappers.query();
            scoreQueryWrapper.lambda().eq(HkAssessmentScore::getScoreState,2).eq(HkAssessmentScore::getIsCurrentAssessment,1)
                    .in(scoreIds.size() > 0,HkAssessmentScore::getProcessInstanceId,scoreIds);
            Page<HkAssessmentScore> euVoyagePage = new Page<>(page.getPageNumber(), page.getPageSize());
            Page<HkAssessmentScore> hkAssessmentScorePage = hkAssessmentScoreMapper.selectPage(euVoyagePage, scoreQueryWrapper);
            List<HkAssessmentScore> records = hkAssessmentScorePage.getRecords();
            records.forEach(hkAssessmentScore -> {
                if (processIds.contains(hkAssessmentScore.getProcessInstanceId())) {
                    hkAssessmentScore.setScoreState(PerformanceConstant.T0_BE_REVIEWED);
                    hkAssessmentScore.setTaskId(hkAssessmentScore.getProcessInstanceId());
                } else {
                    if (hkAssessmentScore.getScoreState().equals("2")) {
                        hkAssessmentScore.setScoreState(PerformanceConstant.END_OF_ASSESSMENT);
                    } else {
                        hkAssessmentScore.setScoreState(PerformanceConstant.ALREADY_APPROVED);
                    }
                }
            });
            Page<HkAssessmentScore> hkAssessmentScorePage1 = hkAssessmentScorePage.setRecords(records);
            return hkAssessmentScorePage1;
        }else if (paramVo.getDepartType() == 1) {
            String departId = paramVo.getDepartIds();
            QueryWrapper<HkAssessmentInfo> query = Wrappers.query();
            query.lambda().eq(HkAssessmentInfo::getAssessmentStatus,2)
                    .in(HkAssessmentInfo::getDepartmentId,departId)
                    .apply(StringUtils.isNotBlank(dateTime.beginDate),
                    "date_format (create_time,'%Y-%m-%d %H:%i:%s') >= date_format('" + dateTime.beginDate + "','%Y-%m-%d %H:%i:%s')")
                    .apply(StringUtils.isNotBlank(dateTime.endDate),
                            "date_format (create_time,'%Y-%m-%d %H:%i:%s') <= date_format('" + dateTime.endDate + "','%Y-%m-%d %H:%i:%s')");
            Page<HkAssessmentInfo> euVoyagePage = new Page<>(page.getPageNumber(), page.getPageSize());
            Page hkAssessmentInfoPage = hkAssessmentInfoMapper.selectPage(euVoyagePage, query);
            List<HkAssessmentInfo> otherParma = getOtherParma(hkAssessmentInfoPage.getRecords(), processIds);
            Page page1 = hkAssessmentInfoPage.setRecords(otherParma);
            return page1;
        }else {
            List<String> departmentIdByLoginUser = hontDepartmentMapper.getDepartmentIdByLoginUser(departmentIds);
            QueryWrapper<HkAssessmentInfo> query = Wrappers.query();
            query.lambda().eq(HkAssessmentInfo::getAssessmentStatus,2)
                    .in(HkAssessmentInfo::getDepartmentId,departmentIdByLoginUser)
                    .apply(StringUtils.isNotBlank(dateTime.beginDate),
                    "date_format (create_time,'%Y-%m-%d %H:%i:%s') >= date_format('" + dateTime.beginDate + "','%Y-%m-%d %H:%i:%s')")
                    .apply(StringUtils.isNotBlank(dateTime.endDate),
                            "date_format (create_time,'%Y-%m-%d %H:%i:%s') <= date_format('" + dateTime.endDate + "','%Y-%m-%d %H:%i:%s')");
            Page<HkAssessmentInfo> euVoyagePage = new Page<>(page.getPageNumber(), page.getPageSize());
            Page<HkAssessmentInfo> hkAssessmentInfoPage = hkAssessmentInfoMapper.selectPage(euVoyagePage, query);
            List<HkAssessmentInfo> otherParma = getOtherParma(hkAssessmentInfoPage.getRecords(), processIds);
            Page page1 = hkAssessmentInfoPage.setRecords(otherParma);
            return page1;
        }
    }
    public List<HkAssessmentInfo>  getOtherParma(List<HkAssessmentInfo> hkAssessmentInfos,List<String> processIds){
        hkAssessmentInfos.forEach(hkAssessmentInfo -> {
            if (processIds.contains(hkAssessmentInfo.getProcessInstanceId())) {
                hkAssessmentInfo.setScoreState(PerformanceConstant.T0_BE_REVIEWED);
                hkAssessmentInfo.setTaskId(hkAssessmentInfo.getProcessInstanceId());
            } else {
                if (hkAssessmentInfo.getAssessmentStatus().equals("2")) {
                    hkAssessmentInfo.setScoreState(PerformanceConstant.END_OF_ASSESSMENT);
                } else {
                    hkAssessmentInfo.setScoreState(PerformanceConstant.ALREADY_APPROVED);
                }
            }
        });

        return hkAssessmentInfos;
    }
    @Override
    public Map<String,Object> getPersonPerformanceCountScoreByDate(ParamVo paramVo){
        String id = feignInterface.remoteUserInfo().getId();
        Result<Map<String, Object>> mapResult = feignInterface.performanceUserInfo();
        Map<String, Object> result = mapResult.getResult();
        String identity = result.get("identity").toString();
        int i = Integer.parseInt(identity);
        List<String> departmentIds =  new ArrayList<>();
        Map<String,Object> resultMap = new HashMap<>();
        ParamVo dateTime = getDateTime(paramVo);
        if (paramVo.getDepartType() == 0){

        }else if (paramVo.getDepartType() == 2){
            List<String> interfaceDepartmentIds = feignInterface.getDepartmentIds();
            departmentIds.addAll(interfaceDepartmentIds);
        }else {
            if (i > 2 && i < 6){
                List<String> list = Arrays.asList(paramVo.getDepartIds().split(","));
                departmentIds.addAll(list);
                if (list.size() > 0){
                    String bottomAvgByDepartment = flowInstanceinfoMapper.getBottomAvgByDepartment(departmentIds, dateTime.getBeginDate(), dateTime.getEndDate());
                    if (StringUtils.isNotBlank(bottomAvgByDepartment)){
                        resultMap.put("date",bottomAvgByDepartment + "h");
                    }else {
                        resultMap.put("date","0h");
                    }
                }else {
                    resultMap.put("date","0h");
                }
            }
            List<String> list = Arrays.asList(paramVo.getDepartIds().split(","));
            departmentIds.addAll(list);
        }

        if (paramVo.getDepartType() == 2){
            if (departmentIds.size() > 0){
                String bottomAvgByDepartment = flowInstanceinfoMapper.getBottomAvgByDepartment(departmentIds, dateTime.getBeginDate(), dateTime.getEndDate());
                if (StringUtils.isNotBlank(bottomAvgByDepartment)){
                    resultMap.put("date",bottomAvgByDepartment + "h");
                }else {
                    resultMap.put("date","0h");
                }
            }else {
                resultMap.put("date","0h");
            }


        }


        Map<String, Integer> stringIntegerMapPositive =
                hkAssessmentScoreMapper.selectScoreByHontUserOnDepartementPositive(dateTime.getBeginDate(),dateTime.getEndDate(),
                        departmentIds, id);

        if (stringIntegerMapPositive != null){
            resultMap.put("positive", stringIntegerMapPositive.get("Sum1"));
            resultMap.put("minus", stringIntegerMapPositive.get("Sum2"));
        } else {
            resultMap.put("positive", 0);
            resultMap.put("minus", 0);
        }

        return resultMap;
    }

    @Override
    public Map<String,Object> getHistoryNumPerformanceByDate(ParamVo paramVo){
        String id = feignInterface.remoteUserInfo().getId();
        List<String> departmentIds =  new ArrayList<>();
        Map<String,Object> resultMap = new HashMap<>();
        ParamVo dateTime = getDateTime(paramVo);
        if (paramVo.getDepartType() == 1){
            QueryWrapper<HkAssessmentInfo> query = Wrappers.query();
            query.select("count(hont_user_id) as num,nick_name,process_instance_id");
            query.lambda().eq(HkAssessmentInfo::getAssessmentStatus,2)
                    .like(HkAssessmentInfo::getDepartmentId,paramVo.getDepartIds())
                    .apply(StringUtils.isNotBlank(dateTime.beginDate),
                    "date_format (create_time,'%Y-%m-%d %H:%i:%s') >= date_format('" + dateTime.beginDate + "','%Y-%m-%d %H:%i:%s')")
                    .apply(StringUtils.isNotBlank(dateTime.endDate),
                            "date_format (create_time,'%Y-%m-%d %H:%i:%s') <= date_format('" + dateTime.endDate + "','%Y-%m-%d %H:%i:%s')")
                    .groupBy(HkAssessmentInfo::getHontUserId);
            List<HkAssessmentInfo> hkAssessmentInfos = hkAssessmentInfoMapper.selectList(query);
            if (hkAssessmentInfos.size() > 0){
                List<String> users = new ArrayList<>();
                List<Integer> nums = new ArrayList<>();
                hkAssessmentInfos.forEach(hkAssessmentInfo -> {
                    users.add(hkAssessmentInfo.getNickName());
                    nums.add(hkAssessmentInfo.getNum());
                });
                Map<String,Object> series = new HashMap<>();
                series.put("name","考核次数");
                series.put("data",nums);
                List<Object> seriesList = new ArrayList<>();
                seriesList.add(series);
                resultMap.put("categories",users);
                resultMap.put("series",seriesList);
            }else {
                resultMap.put("categories",new ArrayList<>());
                resultMap.put("series",new ArrayList<>());
            }

        }else if (paramVo.getDepartType() == 2) {
            List<String> interfaceDepartmentIds = feignInterface.getDepartmentIds();
            List<String> departmentIdByLoginUser = hontDepartmentMapper.getDepartmentIdByLoginUser(interfaceDepartmentIds);
            QueryWrapper<HkAssessmentInfo> query = Wrappers.query();
            query.select("count(department_id) as num,department_title");
            query.lambda().eq(HkAssessmentInfo::getAssessmentStatus,2)
                    .in(HkAssessmentInfo::getDepartmentId,departmentIdByLoginUser)
                    .apply(StringUtils.isNotBlank(dateTime.beginDate),
                            "date_format (create_time,'%Y-%m-%d %H:%i:%s') >= date_format('" + dateTime.beginDate + "','%Y-%m-%d %H:%i:%s')")
                    .apply(StringUtils.isNotBlank(dateTime.endDate),
                            "date_format (create_time,'%Y-%m-%d %H:%i:%s') <= date_format('" + dateTime.endDate + "','%Y-%m-%d %H:%i:%s')")
                    .groupBy(HkAssessmentInfo::getDepartmentId);
            List<HkAssessmentInfo> hkAssessmentInfos = hkAssessmentInfoMapper.selectList(query);
            if (hkAssessmentInfos.size() > 0) {
                List<String> departs = new ArrayList<>();
                List<Integer> nums = new ArrayList<>();
                hkAssessmentInfos.forEach(hkAssessmentInfo -> {
                    departs.add(hkAssessmentInfo.getDepartmentTitle());
                    nums.add(hkAssessmentInfo.getNum());
                });
                Map<String, Object> series = new HashMap<>();
                series.put("name", "考核次数");
                series.put("data", nums);
                List<Object> seriesList = new ArrayList<>();
                seriesList.add(series);
                resultMap.put("categories", departs);
                resultMap.put("series", seriesList);
            }else {
                resultMap.put("categories",new ArrayList<>());
                resultMap.put("series",new ArrayList<>());
            }
        }
        return resultMap;
    }
}
